package com.socket.server;

/**
 * @author wangg
 * @date 2019/4/9 13:48
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadFactory;

/**
 * 阻塞 BIO
 */
class BsocketServer {
    private final int PORT;
    private ThreadFactory tFactory = r -> {
        Thread thread = new Thread(r);
        thread.setName("BsocketServer_" + thread.getId());
        return thread;
    };

    public BsocketServer(int port) {
        this.PORT = port;
    }

    public void bSocketServer() {
        ServerSocket server = null;
        try {
            server = new ServerSocket(this.PORT);
            System.out.println(" blocked Socket start...");
            Socket socket = server.accept();
            tFactory.newThread(() -> {
                BufferedReader in = null;
                PrintWriter out = null;
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream());
                    String body = null;
                    while (true) {
                        body = in.readLine();
                        if (null == body) {
                            break;
                        }
                        System.out.println("blocked Socket Server: " + body);
                        out.println("收到：" + body);
                        out.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (out != null) {
                        out.close();
                    }
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
